package com.sparrow.source.service.impl;

import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sparrow.source.persistense.IasPerson;
import com.sparrow.source.persistense.IasUser;
import com.sparrow.source.persistense.mapper.IasPersonMapper;
import com.sparrow.source.service.IIasPersonService;
import org.apache.commons.compress.utils.Lists;
import org.apache.ibatis.binding.MapperMethod;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author bryceyung
 * @since 2024/11/27
 */
@Service
public class IasPersonServiceImpl extends ServiceImpl<IasPersonMapper, IasPerson> implements IIasPersonService {

    @Override
    public Boolean saveOrUpdateBatchByPersonId(List<IasPerson> personList) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
        Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
        return executeBatch(personList, DEFAULT_BATCH_SIZE, (sqlSession, entity) -> {
            Object personIdVal = ReflectionKit.getFieldValue(entity, "personId");
            if (StringUtils.checkValNull(personIdVal) || Objects.isNull(getByPersonId((Long) personIdVal))) {
                sqlSession.insert(tableInfo.getSqlStatement(SqlMethod.INSERT_ONE.getMethod()), entity);
            } else {
                MapperMethod.ParamMap<IasPerson> param = new MapperMethod.ParamMap<>();
                param.put(Constants.ENTITY, entity);
                sqlSession.update(tableInfo.getSqlStatement(SqlMethod.UPDATE_BY_ID.getMethod()), param);
            }
        });
    }

    @Override
    public IasPerson getByPersonId(Long personId) {
        return lambdaQuery().eq(IasPerson::getPersonId, personId).one();
    }

    @Override
    public Boolean uploadUnvPerson(List<IasPerson> personList) {
        List<IasPerson> persons = Lists.newArrayList();
        personList.forEach(data -> {
            //UNV上生成的personId值与feiyou uid位数不一样
            if (data.getPersonId() > Integer.MAX_VALUE) {
                persons.add(data);
            }
        });
        return saveOrUpdateBatchByPersonId(persons);
    }
}
